package com.dianxun.bookmanager.ui.activity;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.bottomnavigation.LabelVisibilityMode;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.TextView;

import com.dianxun.bookmanager.R;
import com.dianxun.bookmanager.common.base.BaseActivity;
import com.dianxun.bookmanager.ui.fragment.BookLibFragment;
import com.dianxun.bookmanager.ui.fragment.BorrowingFragment;
import com.dianxun.bookmanager.ui.fragment.OverdueFragment;
import com.dianxun.bookmanager.ui.fragment.RetFragment;
import com.dianxun.bookmanager.ui.widget.NoScrollViewPager;
import com.dianxun.bookmanager.utils.ISO15693;
import com.dianxun.bookmanager.utils.NfcUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainManagerActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.viewpager)
    NoScrollViewPager mViewPager;
    @BindView(R.id.bottom_navigation)
    BottomNavigationView bottomNavigationView;
    private FragmentPagerAdapter fragmentPagerAdapter;
    private List<Fragment> mFragment = new ArrayList<>(4);
    BorrowingFragment borrowingFragment;
    RetFragment retFragment;
    OverdueFragment overdueFragment;
    BookLibFragment bookLibFragment;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private Tag detectedTag;
    private String strId;

    @Override
    protected int getContentView() {
        return R.layout.activity_main_manager;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return getString(R.string.borrowing);
                    case 1:
                        return getString(R.string.ret);
                    case 2:
                        return getString(R.string.overdue);
                    case 3:
                        return getString(R.string.book_libing);
                }
                return super.getPageTitle(position);
            }
        };

        bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.item_borrowing:
                                mViewPager.setCurrentItem(0, false);
                                tv_title.setText(fragmentPagerAdapter.getPageTitle(0));
                                return true;
                            case R.id.item_ret:
                                mViewPager.setCurrentItem(1, false);
                                tv_title.setText(fragmentPagerAdapter.getPageTitle(1));
                                return true;
                            case R.id.item_overdue:
                                mViewPager.setCurrentItem(2, false);
                                tv_title.setText(fragmentPagerAdapter.getPageTitle(2));
                                return true;
                            case R.id.item_book_lib:
                                mViewPager.setCurrentItem(3, false);
                                tv_title.setText(fragmentPagerAdapter.getPageTitle(3));
                                return true;
                        }
                        return false;
                    }
                });

        borrowingFragment = new BorrowingFragment();
        mFragment.add(borrowingFragment);
        retFragment = new RetFragment();
        mFragment.add(retFragment);
        overdueFragment = new OverdueFragment();
        mFragment.add(overdueFragment);
        bookLibFragment = new BookLibFragment();
        mFragment.add(bookLibFragment);
        mViewPager.setAdapter(fragmentPagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {/*empty*/}

            @Override
            public void onPageSelected(int position) {
                tv_title.setText(fragmentPagerAdapter.getPageTitle(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() != null) {
                String qrcode = result.getContents();
                if (mViewPager.getCurrentItem() == 0) {
                    borrowingFragment.getBookInfoByBarNo(qrcode);
                } else if (mViewPager.getCurrentItem() == 1) {
                    retFragment.getBookInfoByBarNo(qrcode);
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 启动Activity，界面可见时
     */
    @Override
    public void onStart() {
        super.onStart();
        mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
        //一旦截获NFC消息，就会通过PendingIntent调用窗口
        mPendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, getClass()), 0);
    }

    /**
     * 获得焦点，按钮可以点击
     */
    @Override
    public void onResume() {
        super.onResume();
        //设置处理优于所有其他NFC的处理
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(self, mPendingIntent, null, null);
    }

    /**
     * 暂停Activity，界面获取焦点，按钮可以点击
     */
    @Override
    public void onPause() {
        super.onPause();
        //恢复默认状态
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(self);
    }

    @Override
    public void onNewIntent(Intent intent) {
        //1.获取Tag对象
        detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (detectedTag != null) {
            strId = NfcUtils.bytesToHexString(detectedTag.getId());

//            = NfcUtils.readNfcTag(intent);
            if (TextUtils.isEmpty(strId)) {
                toast("无法获取NFC");
            } else {
//            NdefMessage ndefMessage = new NdefMessage(
//                    new NdefRecord[]{NfcUtils.createTextRecord("AAA")});
//            boolean result = NfcUtils.writeTag(ndefMessage, detectedTag);
//            if (result) {
//                toast("写入成功");
//            } else {
//                toast("写入失败");
//            }

                if (mViewPager.getCurrentItem() == 0) {
                    if (borrowingFragment.nfcProgressDialog != null && borrowingFragment.nfcProgressDialog.isShowing()) {
//                        borrowingFragment.getBookInfoByRfidNo(nfcText);
                    }
                    if (borrowingFragment.rfidProgressDialog != null && borrowingFragment.rfidProgressDialog.isShowing()) {
                        String nfcText = "";
                        //2.获取Ndef的实例
                        ISO15693 iso15693 = null;
                        NfcV nfcv = NfcV.get(detectedTag);
                        try {
                            nfcv.connect();
                            iso15693 = new ISO15693(nfcv);
                            nfcText = iso15693.readBookInfo();
                        } catch (IOException e) {
//                toast("读取标签失败！");
                            e.printStackTrace();
                        } finally {
                            try {
                                nfcv.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        borrowingFragment.getBookInfoByRfidNo(nfcText);
                    }
                } else if (mViewPager.getCurrentItem() == 1) {
                    if (retFragment.progressDialog != null && retFragment.progressDialog.isShowing()) {
                        String nfcText = "";
                        //2.获取Ndef的实例
                        ISO15693 iso15693 = null;
                        NfcV nfcv = NfcV.get(detectedTag);
                        try {
                            nfcv.connect();
                            iso15693 = new ISO15693(nfcv);
                            nfcText = iso15693.readBookInfo();
                        } catch (IOException e) {
//                toast("读取标签失败！");
                            e.printStackTrace();
                        } finally {
                            try {
                                nfcv.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        retFragment.getBookInfoByRfidNo(nfcText);
                    }
                }
            }
        }
    }

    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                toast("再按一次退出程序");
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
